package com.yuntian.controller;

import com.yuntian.dto.ProductOrderDataDto;
import com.yuntian.exception.BusinessException;
import com.yuntian.exception.MonthIllegalException;
import com.yuntian.exception.NoDataException;
import com.yuntian.service.ProductMonthReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class ProductMonthReportController {

    private static final Logger logger = LoggerFactory.getLogger(CustomerMonthReportController.class);

    @Autowired
    private ProductMonthReportService productMonthReportService;


    @GetMapping("/PR10401")
    public String getCustomerOrderTimePage(){
        logger.info("PR10401页面请求已接收");
        return "PR10401"; // 返回 templates/PR10401.html
    }

    @PostMapping("/PR10401/submit")

    public String submitPR10401(@RequestParam(name = "year", required = false) Integer year, @RequestParam(name = "month", required = false) Integer month, Model model) {
        logger.info("PR10301表单提交：year={}, month={}", year, month);
        try {
            // 查询客户受注数据
            List<ProductOrderDataDto> orderDataList = productMonthReportService.getProductOrderData(year, month);
            // 计算总合計（所有客户受注额之和）
            BigDecimal totalAmount = orderDataList.stream().map(ProductOrderDataDto::getSum)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 将数据放入Model，传递到PR10402页面
            model.addAttribute("orderDataList", orderDataList);
            model.addAttribute("totalAmount", totalAmount);
            model.addAttribute("currentYear", year);
            model.addAttribute("currentMonth", month);

            // 跳转到PR10402页面
            return "HTML/PR10402"; // 对应templates/HTML/PR10402.html
        } catch (MonthIllegalException | NoDataException | BusinessException e) {
            // 业务异常：返回PR10401页面并显示错误信息
            model.addAttribute("errorMsg", e.getMessage());
            return "PR10401";
        }
    }
}
